package jdbc;

import cn.itcast.dao.DaoException;
import utils.JdbcUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MetaDataDemo {

    public static void main(String[] args) throws ClassNotFoundException {
        System.out.println(read("select * from user"));
    }

    static List<Map<String,Object>> read(String sql) throws ClassNotFoundException {
        // 初始化
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();

            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            String[] columnNames = new String[columnCount];
            for (int i=1; i<=columnCount; i++)
                columnNames[i-1] = rsmd.getColumnLabel(i);

            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
            Map<String, Object> data = new HashMap<String, Object>();

            while (rs.next()) {
                for (int i = 0; i<columnCount;i++){
                    String columnName = columnNames[i];
                    Object obj = rs.getObject(columnName);
                    data.put(columnName, obj);
                }
                datas.add(data);
            }
            return datas;
        } catch (SQLException e) {
            throw new DaoException(e);
        }finally {
            JdbcUtils.free(ps, conn, null);
        }

    }
}
